package com.pan.download2;

import com.pan.download2.entiry.ChapterInfo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class Page implements Runnable{

    private EdgeDriver edgeDriver;
    private List<ChapterInfo> chapterInfoList;//目录章节链接的列表

    private Integer start;//开始爬的章节

    private Integer step;//步长

    private Write write;//写入的类



    public Page(List<ChapterInfo> chapterInfoList, Integer start, Integer step, Write write) {

        this.chapterInfoList = chapterInfoList;
        this.start = start;
        this.step = step;
        this.write = write;

    }


    @Override
    public void run() {
        edgeDriver = new EdgeDriver();
        for (int i = start; i < chapterInfoList.size(); i+=step) {
            String url = chapterInfoList.get(i).getUrl();
            String title = chapterInfoList.get(i).getTitle();
//            System.out.println(title + " 开始下载");
            edgeDriver.navigate().to(url);
            edgeDriver.findElement(By.className("footer"));
            WebElement contentElement = edgeDriver.findElement(By.id("content"));
            contentElement.findElement(By.cssSelector("a"));
            String content = contentElement.getText();
            //要删除的字符串
            content = "\n\n\n\n\n\n\n\n" + title +"\n\n\n\n" + content;
            while (true) {
                if (!write.appendNextContent(i, content)) {
                    LockSupport.park();//写入不成功则阻塞，等等被唤醒后再次写入
                    continue;
                }
                break;
            }
            System.out.println(i+"."+title+" 下载完成");
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        edgeDriver.quit();
    }
}
